<template>
  <div class="department-container">
    <div class="app-container">

      <PageTools>
        <!-- <template #left> -->
        <template slot="left">
          总记录数：{{ total }}
        </template>
        <template #right>
          <el-button v-allow="'import_employee'" type="warning" size="small" @click="$router.push('/import')">导入excel</el-button>
          <el-button v-allow="'export_employee'" type="danger" size="small" @click="hExportExcel">导出excel</el-button>
          <el-button type="primary" size="small" @click="showDialog=true">新增员工</el-button>
        </template>
      </PageTools>

      <el-card style="margin-top: 10px;">
        <el-table border :data="list">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="姓名">
            <template slot-scope="scope">
              <!-- <img :src="scope.row.staffPhoto" alt=""> -->

              <image-holder :src="scope.row.staffPhoto" />

            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式">
            <template slot-scope="scope">
              {{ formatEmployment(scope.row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" />
          <el-table-column label="操作" width="280">
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="$router.push('/employees/detail?id='+scope.row.id)">查看 </el-button>
              <!-- 第二种写法 -->
              <!-- <el-button type="text" size="small" @click="$router.push('/employees/detail-id/'+scope.row.id)">查看-动态路由参数</el-button> -->
              <el-button type="text" size="small" @click="hAssignRole(scope.row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->

        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            layout="prev, pager, next"
            :total="total"
            :page-size="pageParams.size"
            @current-change="hCurrentChange"
          />
        </el-row>
      </el-card>
    </div>
    <el-dialog
      title="新增员工"
      :visible.sync="showDialog"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close="hClose"
    >
      <addor-edit
        ref="refAdd"
        @update-empolyee="hUpdateEmpolyee"
        @close="showDialog=false"
      />
    </el-dialog>
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="showDialogRole"
      @close="hClosea"
    >
      <!-- v-if="showDialogRole" -->
      <assign-role
        ref="assignRole"
        :employee-id="curEmployeId"
        @close="showDialogRole=false"
        @update-close="hUpdateClose"
      />
    </el-dialog>

  </div>
</template>
<script>
// 获取员工信息,删除
import { getEmployeeList, delEmployee } from '@/api/employees'
import EmployeeEnum from '@/constant/employees'
import addorEdit from './empDialog'
import AssignRole from './assignRole.vue'
// console.log(EmployeeEnum)
const hireType = {}
EmployeeEnum.hireType.forEach(item => {
  hireType[item.id] = item.value
})
export default {
  components: {
    addorEdit, AssignRole
  },
  data() {
    return {
      curEmployeId: '', // 保存分配角色的id
      list: [], // 保存所有员工信息
      total: 0, // 表示总条目数
      pageParams: { // 分页
        page: 1,
        size: 5
      },
      showDialog: false, // 弹窗
      showDialogRole: false // 控制分配角色弹窗
    }
  },
  created() {
    this.loadEmployeeList()
  },
  methods: {
    // 获取员工列表
    async loadEmployeeList() {
      try {
        const res = await getEmployeeList(this.pageParams)
        this.list = res.data.rows
        this.total = res.data.total
      } catch (err) {
        console.log(err)
      }
      // console.log(res)
    },
    // 删除员工信息方法
    async doDel(id) {
      try {
        await delEmployee(id)

        if (this.list.length === 1) {
          this.pageParams.page--
          if (this.pageParams.page <= 0) {
            this.pageParams.page = 1
          }
        }

        this.$message.success('删除成功')
        this.loadEmployeeList()
        // console.log(res)
      } catch (err) {
        this.$message.error('删除失败')
        console.log(err)
      }
    },
    formatEmployment(id) {
      return hireType[id]
    },
    // 删除员工信息功能
    hDel(id) {
      console.log('要删除的id', id)
      this.$confirm('此操作将永久删除员工, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 做删除
        this.doDel(id)
      }).catch(() => {

      })
    },
    // 翻页的回调
    hCurrentChange(arr) { // 翻页的页码
      // 把当前的页码赋值给请求是需要的参数
      this.pageParams.page = arr
      // 重新加载数据
      this.loadEmployeeList()
    },
    // 添加成功时的回调
    hUpdateEmpolyee() {
      this.showDialog = false
      this.loadEmployeeList()
    },
    // 弹窗关闭时执行子组件的事件
    hClose() {
      this.$refs.refAdd.resetForm()
    },
    hClosea() {
      this.$refs.assignRole.abc()
    },
    // 导出事件
    async hExportExcel() {
      // 获取数据
      const res = await getEmployeeList(this.pageParams)
      const obj = this.transData(res.data.rows)

      import('@/vendor/Export2Excel').then(excel => {
        // excel表示导入的模块对象
        console.log(excel)
        excel.export_json_to_excel({
          header: obj.header, // 表头 必填
          data: obj.data, // 具体数据 必填
          filename: 'excel-list', // 文件名称
          autoWidth: true, // 宽度是否自适应
          bookType: 'xlsx' // 生成的文件类型
        })
      })
    },

    // 导出数据转换
    transData(rows) {
      const map = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }
      const enKeys = Object.keys(rows[0])

      const header = enKeys.map(enKey => map[enKey])

      const data = rows.map(obj => Object.values(obj))

      return { header, data }
    },
    // 分配角色按钮
    hAssignRole(id) {
      console.log(id)
      this.showDialogRole = true
      // 保存分配角色的id
      this.curEmployeId = id
      this.$nextTick(() => {
        this.$refs.assignRole.loadRoles()
      })
    },
    // 用户分配角色成功
    hUpdateClose() {
      this.showDialogRole = false
      this.loadEmployeeList()
    }
  }
}
</script>
<style scoped>

</style>
